package com.eastcom.collection.provider;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.beans.BeansException
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.beans.factory.support.BeanDefinitionBuilder
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.ConfigurableApplicationContext

public class DynamicBeanRegisterProvider implements ApplicationContextAware {
	private ApplicationContext context;
	private static Log log = LogFactory.getLog(DynamicBeanRegisterProvider.class);
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }
 
    public void addBeanService(String beanName, String className,Map<String,Object> propertyMap) {
        if (!context.containsBean(beanName)) {
            Class<?> serviceClass = getServiceClass(className);
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass);
			if(propertyMap != null){
				propertyMap.each {
					key,value->
					beanDefinitionBuilder.addPropertyValue(key, value);
				}
			}
            registerBean(beanName, beanDefinitionBuilder.getBeanDefinition());
        }
 
    }
	
	public void addBeanService(String beanName, Class<?> clazz,Map<String,Object> propertyMap) {
		if (!context.containsBean(beanName)) {
			BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
			if(propertyMap != null){
				propertyMap.each {
					key,value->
					beanDefinitionBuilder.addPropertyValue(key, value);
				}
			}
			registerBean(beanName, beanDefinitionBuilder.getBeanDefinition());
		}
 
	}
 
    /**
     * @desc 向spring容器注册bean
     * @param beanName
     * @param beanDefinition
     */
    private void registerBean(String beanName, BeanDefinition beanDefinition) {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) context;
        BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext
                .getBeanFactory();
        beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);
    }
 
    /**
     * @desc 根据类名查找class
     * @param className
     * @return
     * @throws BVSException
     */
    private Class<?> getServiceClass(String className){
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            log.error("not found service class:" + className, e);
        }
		return null;
    }
}
